package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;


@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        // 解决缓存穿透
        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

//        // 解决缓存击穿
//        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);




        if(shop == null){
            return Result.fail("店铺不存在");
        }
        // 成功则返回
        return Result.ok(shop);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /*
      缓存 + 缓存逻辑过期<防止缓存击穿，获取锁的去数据库查询信息，未获取锁的返回过期信息>
     */
    public Shop queryWithLogicalExpire(Long id){
        String shopKey = CACHE_SHOP_KEY + id;
        String lockKey = LOCK_SHOP_KEY + id;
        // 从Redis中查询
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);

        if (StrUtil.isBlank(shopJson)){
            // 缓存未命中，返回错误
            return null;
        }

        // 把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            // 未过期，返回
            return shop;
        }

        // 已过期，缓存重建

        // 获取互斥锁
        boolean islock = tryLock(lockKey);
        if (islock) {
            // 成功，开启独立线程更新缓存
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                // 重建缓存
                try {
                    this.saveShopToRedis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    unLock(lockKey);
                }
            });
        }
        return shop;
    }

    /*
      缓存 + 缓存互斥锁<防止缓存击穿>
     */
    public Shop queryWithMutex(Long id){
        String shopKey = CACHE_SHOP_KEY + id;
        // 从Redis中查询
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        // 判断是否存在
        if (StrUtil.isNotBlank(shopJson)){
            // 存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            // 重置过期时间
            stringRedisTemplate.expire(shopKey, CACHE_SHOP_TTL, TimeUnit.MINUTES);
            return shop;
        }

        // 判断是否是写入的空缓存
        if (shopJson != null){  // 三种情况， 有信息，空字符串，空引号""
            return null;
        }

        // 查询数据库前，判断有没有互斥锁
        // 获取互斥锁，判断有没有成功
        String lockKey = LOCK_SHOP_KEY + id;
        try {
            boolean islock = tryLock(lockKey);
            if (!islock){
                // 未获取，休眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            // 成功获取，查询数据库


            // 根据id查询数据库
            Shop shop = getById(id);
            // 模拟缓存延迟写入
            Thread.sleep(50);
            // 不存在，返回报错
            if (shop == null){
                // 向redis中写入一个空值以预防缓存穿透
                stringRedisTemplate.opsForValue().set(shopKey, "",  RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                // 返回错误信息
                return null;
            }
            // 存在，取出来保存Redis中
            stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop));
            stringRedisTemplate.expire(shopKey, CACHE_SHOP_TTL, TimeUnit.MINUTES);

            // 释放互斥锁
            unLock(lockKey);

            return shop;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 即使异常也要释放互斥锁
            unLock(lockKey);
        }
    }




    /*
      缓存 + 缓存空对象<防止缓存穿透>
     */
    public Shop queryWithPassThrough(Long id){
        // 从Redis中查询
        String shopKey = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);
        // 判断是否存在
        if (StrUtil.isNotBlank(shopJson)){
            // 存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            // 重置过期时间
            stringRedisTemplate.expire(shopKey, CACHE_SHOP_TTL, TimeUnit.MINUTES);
            return shop;
        }

        // 判断是否是写入的空缓存
        if (shopJson != null){  // 三种情况， 有信息，空字符串，空引号""
            return null;
        }

        // 不存在，根据id查询数据库
        Shop shop = getById(id);
        // 不存在，返回报错
        if (shop == null){
            // 向redis中写入一个空值以预防缓存穿透
            stringRedisTemplate.opsForValue().set(shopKey, "",  RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            // 返回错误信息
            return null;
        }
        // 存在，取出来保存Redis中
        stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop));
        stringRedisTemplate.expire(shopKey, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }

    private boolean tryLock(String key){
        Boolean flag =  stringRedisTemplate.opsForValue().setIfAbsent(key, "1",  10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private  void unLock(String key){
        stringRedisTemplate.delete(key);
    }


    public void saveShopToRedis(Long id, Long expireSeconds) throws InterruptedException{
        // 查询店铺数据
        Shop shop = getById(id);
        // 封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 保存到Redis中
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
        stringRedisTemplate.expire(CACHE_SHOP_KEY + id, expireSeconds, TimeUnit.SECONDS);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null){
            return Result.fail("店铺id不能为空");
        }
        // 更新数据库
        updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok(200);
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 判断是否根据坐标查询
        if (x == null || y == null){
            // 不根据坐标，直接根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        // 查询redis 按距离排序，分页，结果，shopId,distance
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(key, GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        // 解析出Id
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(list.size() <= from){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<String, Distance>(list.size());
        list.stream().skip(from).forEach(result -> {
            String shopIdStr = result.getContent().getName();
            ids.add(Long.parseLong(shopIdStr));
            // 获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 根据id查询shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        //返回
        return Result.ok(shops);
    }
}
